package com.wlr.blog.article.controller;

import com.wlr.blog.util.common.aspect.LogTrack;
import com.wlr.blog.util.common.dto.Result;
import com.wlr.blog.util.common.enums.MailEnum;
import com.wlr.blog.web.common.dto.MailRequest;
import com.wlr.blog.web.common.service.SendMailService;
import com.wlr.blog.web.common.utils.MailUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author lrwang
 * @version 1.0
 * @date 2022/12/7 15:37
 */
@RestController
@RequestMapping("/mail")
public class MailController {
    @Autowired
    SendMailService sendMailService;

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/send")
    @LogTrack(topic = "register", key = "register")
    public Result<?> sendMail(@RequestParam("username") String mailPath) {
        MailRequest mailRequest = new MailRequest();
        String verifyCode = MailUtils.generateCode(4);
        mailRequest.setText(MailEnum.VALID_CODE.getSubject() + "注册验证码为：" + verifyCode + "<>此");
        mailRequest.setSendTo(mailPath);
        mailRequest.setSubject(MailEnum.VALID_CODE.getSubject());
        try {
            redisTemplate.opsForValue().set("verifyCode#" + mailPath, verifyCode, 5, TimeUnit.MINUTES);
            sendMailService.sendSimpleMail(mailRequest);
            return Result.success("邮件发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("邮件发送失败");
        }
    }
}
